package com.example.googlemapdrawroutelast;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class RouteAdapter extends ArrayAdapter<RouteInfo> {
	private final Context context;
	private List<RouteInfo> routes;
	private List<RouteInfo> displayedRoutes = new ArrayList<RouteInfo>();
	ApplicationData appData;

	public RouteAdapter(Context context, List<RouteInfo> routes,
			ApplicationData appData) {
		super(context, R.layout.simplerow, routes);
		this.context = context;
		this.routes = routes;
		this.displayedRoutes.addAll(routes);
		this.appData = appData;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View rowView = inflater.inflate(R.layout.simplerow, parent, false);
		TextView textView = (TextView) rowView.findViewById(R.id.rowTextView);
		textView.setText(displayedRoutes.get(position).getName());
		return rowView;
	}

	@Override
	public int getCount() {
		return displayedRoutes.size();
	}

	@Override
	public RouteInfo getItem(int position) {
		return displayedRoutes.get(position);
	}
	
	private RouteInfo getRouteInfoById(int id)
	{
		for (RouteInfo routeInfo : displayedRoutes) 
		{
			if (routeInfo.getId() == id)
			{
				return routeInfo;
			}
		}
		return null;
	}
	
	public void changeDescription(String name, String description, int routeId)
	{
		RouteInfo routeInfo = getRouteInfoById(routeId);
		if (routeInfo != null)
		{
			routeInfo.setName(name);
			routeInfo.setDescription(description);		
		}
	}
	
	public void remove(int position) {
		RouteInfo routeInfoToRemove = displayedRoutes.remove(position);
		routes.remove(routeInfoToRemove);
		notifyDataSetChanged();
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	public void displayAll() {
		displayedRoutes.clear();
		
		for (RouteInfo routeInfo : routes) {
			displayedRoutes.add(routeInfo);
		}
		
		notifyDataSetChanged();
		
	}

	public void filter(int userId) {
		displayedRoutes.clear();
		for (RouteInfo routeInfo : routes) {
			if (routeInfo.getId_user() == userId) {
				displayedRoutes.add(routeInfo);
			}
		}
		notifyDataSetChanged();
	}

}